<template>
	<div class="executeTask-box">
		<el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
			<el-tab-pane label="过程意见" name="comments">
				<el-table :data="comments" border fit highlight-current-row style="width: 100%;"
					:cell-style="{padding:'3px'}">
					<el-table-column label="任务节点" prop="taskName" align="center" width="165px">
						<template slot-scope="scope"><span>{{ scope.row.taskName }}</span></template>
					</el-table-column>
					<el-table-column label="操作类型" prop="typeDesc" align="center" width="80px">
						<template slot-scope="scope"><span>{{ scope.row.typeDesc }}</span></template>
					</el-table-column>
					<el-table-column label="参与人" prop="userName" align="center" width="80px">
						<template slot-scope="scope"><span>{{ scope.row.userName }}</span></template>
					</el-table-column>
					<el-table-column label="时间" prop="time" align="center" width="165px">
						<template slot-scope="scope"><span>{{ scope.row.time }}</span></template>
					</el-table-column>
					<el-table-column label="意见" prop="fullMessage" align="left">
						<template slot-scope="scope"><span>{{ scope.row.fullMessage }}</span></template>
					</el-table-column>
				</el-table>
			</el-tab-pane>
			<!-- <el-tab-pane label="流程表单" name="processIntanceForm">
				<div v-if="generateStartFormVisible">
					<form-parser :data="startFormJson" :value="variables" ref="generateStartForm">
					</form-parser>
				</div>
				<el-form label-width="100px" v-if="showBusinessKey">
					<el-form-item label="业务主键Key:">
						<el-input v-model="businessKey" disabled />
					</el-form-item>
				</el-form>
				<div v-if="!generateStartFormVisible&&!showBusinessKey">
					无
				</div>
			</el-tab-pane> -->
			<el-tab-pane label="流程图" name="processIntanceImage">
				<el-scrollbar><img :src="imagePath" alt="流程图"></el-scrollbar>
			</el-tab-pane>
		</el-tabs>


		<select-user ref="selectUser" :visible.sync="selectUserVisible" :appendToBody="true"
			:multipleSelect="selectUserMultipleSelect" @selectUserFinished="selectUserFinished"></select-user>

		<task-back-nodes v-if="dialogTaskBackNodesVisible" :visible.sync="dialogTaskBackNodesVisible"
			:executeTaskId="executeTaskId" @backTaskFinished="backTaskFinished"></task-back-nodes>

		<div slot="footer" style="margin-top: 20px;" class="dialog-footer">
			<el-form :rules="rules" ref="ruleForm" :model="form" label-width="60px" v-if="endTime==null&&assignee!=null&&assignee===$store.getters.sysUser.userId">
				<el-form-item label="抄送给:">
					<el-row align="left">
						<el-col :span="1" align="left">
							<i class="el-icon-plus el-icon--left" style="cursor:pointer" @click="doSelectCcTo"></i>
						</el-col>
						<el-col :span="23" align="left">
							<el-tag v-for="tag in ccToVos" :key="tag.userId" effect="plain" closable
								@close="handleCcToClose(tag)" style="margin-left: 5px">{{tag.userName}}
							</el-tag>
						</el-col>
					</el-row>
				</el-form-item>
				<el-form-item label="意见:" prop="message">
					<el-input v-model="form.message" :autosize="{ minRows: 3, maxRows: 6}" type="textarea"
						placeholder="请输入意见" />
				</el-form-item>
			</el-form>
			<div v-if="endTime==null&&assignee!=null&&assignee===$store.getters.sysUser.userId" style="flex: 1;display: flex;flex-direction: row;justify-content: flex-end;align-items: center;">
				<el-button icon="el-icon-check" type="primary" @click="doComplete">同意并提交</el-button>
				<el-button v-if="buttons.length==0 || buttons.includes('STOP')" icon="el-icon-close" type="primary"
					@click="doStop">终止
				</el-button>
				<el-button v-if="buttons.length==0 || buttons.includes('ASSIGN')" icon="el-icon-user" type="primary"
					@click="doAssign">转办
				</el-button>
				<el-button v-if="buttons.length==0 || buttons.includes('DELEGATE')" icon="el-icon-user" type="primary"
					@click="doDelegate">委派
				</el-button>
				<el-button v-if="!initiator && (buttons.length==0 || buttons.includes('BACK'))" icon="el-icon-back"
					type="primary" @click="doBack">退回
				</el-button>
				<el-button v-permission="'flowable:task:execute'" icon="el-icon-back"
					type="primary" @click.native="btnUnclaim">取消认领
				</el-button>
				<!-- <el-button  icon="el-icon-back"
					type="primary" @click.native="btnRead(row.id)">已阅
				</el-button> -->
			</div>
			<el-button v-permission="'flowable:task:execute'" v-if="endTime==null&&(assignee==null||assignee=='')"
			 type="primary" plain @click.native="btnClaim">认领</el-button>
		</div>
	</div>

</template>

<script>
	import {
		getAction,
		putAction
	} from '@/api/manage'
	import {
		Message
	} from 'element-ui'
	import SelectUser from '@/components/select/SelectUser'
	import CustomError from '@/customError'
	import TaskBackNodes from './TaskBackNodes'
	import FormParser from '@/views/flowable/form/FormParser'
	import {
		getToken
	} from '@/utils/auth'
	export default {
		name: 'ExecuteTask',
		components: {
			SelectUser,
			TaskBackNodes,
			FormParser
		},
		props: {
			visible: {
				type: Boolean,
				default: function() {
					return false
				}
			},
			executeTaskId: {
				type: String,
				default: function() {
					return ''
				}
			},
			processInstanceId: {
				type: String,
				default: function() {
					return ''
				}
			}
		},

		data() {
			return {
				startFormKey: undefined,
				taskFormKey: undefined,
				startUserId: '',
				initiator: false,
				selectUserVisible: false,
				selectUserMultipleSelect: false,
				selectUserType: '',
				message: '',
				ccToVos: [],
				dialogTaskBackNodesVisible: false,
				buttons: [],
				activeName: 'comments',
				comments: [],
				imagePath: '',
				isShowProcessInstanceForm: false,
				generateStartFormVisible: false,
				startFormJson: undefined,
				variables: undefined,
				showBusinessKey: false,
				businessKey: undefined,
				endTime: '',
				assignee: '',
				rules: {
          message: [
            { required: true, message: '请输入意见', trigger: 'blur' }
          ]
        },
				form:{
					message:''
				}
			}
		},
		created() {
			this.init(),
			this.queryClick()
		},
		methods: {
			initData() {
				getAction('/flowable/task/executeTaskData', {
					taskId: this.executeTaskId
				}).then(res => {
					const {
						data
					} = res
					this.startUserId = data.startUserId
					this.startFormKey = data.startFormKey
					this.taskFormKey = data.taskFormKey
					this.initiator = data.initiator
					this.buttons = data.buttons ?? []
				})
			},
			checkMessage() {
				this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            console.log('同意进来了')
          } else {
            console.log('error submit!!');
            return false;
          }
        });
				if (!this.form.message || this.form.message === '') {
					Message.error("请输入意见")
					throw new CustomError("请输入意见")
				}
			},
			doComplete() {
				this.checkMessage()
				if (this.$refs.generateFormTask) {
					this.$refs.generateFormTask.getData().then(values => {
						if (values && values != undefined) {
							let realValues = values
							if (this.startFormKey && this.taskFormKey && this.startFormKey == this.taskFormKey) {
								let processInstanceFormData = JSON.stringify(values)
								realValues = Object.assign({
									processInstanceFormData
								}, values)
							}
							return putAction('/flowable/task/complete', {
								taskId: this.executeTaskId,
								message: this.form.message,
								initiator: this.initiator,
								values: realValues,
								ccToVos: this.ccToVos
							}).then(({
								msg
							}) => {
								Message.success(msg)
								this.$emit("executeTaskFinished");
								this.queryClick()
								this.listComments()
							})
						}
					}).catch(e => {
						console.info(e)
					})
				} else {
					putAction('/flowable/task/complete', {
						taskId: this.executeTaskId,
						message: this.form.message,
						ccToVos: this.ccToVos
					}).then(({
						msg
					}) => {
						Message.success(msg)
						this.$emit("executeTaskFinished");
						this.queryClick()
						this.listComments()
					})
				}
			},
			doStop() {
				this.checkMessage()
				putAction('/flowable/task/stopProcessInstance', {
					taskId: this.executeTaskId,
					message: this.form.message
				}).then(({
					msg
				}) => {
					Message.success(msg)
					this.$emit("executeTaskFinished");
					this.queryClick()
				})
			},
			doSelectCcTo() {
				this.selectUserMultipleSelect = true
				this.selectUserVisible = true
				this.selectUserType = 'selectCcTo'
				if (this.$refs.selectUser.treeData.length == 0) {
					this.$refs.selectUser.getTreeData()
				}
			},
			handleCcToClose(tag) {
				this.ccToVos.splice(this.ccToVos.indexOf(tag), 1);
			},
			doAssign() {
				this.checkMessage()
				this.selectUserMultipleSelect = false
				this.selectUserVisible = true
				this.selectUserType = 'assign'
				if (this.$refs.selectUser.treeData.length == 0) {
					this.$refs.selectUser.getTreeData()
				}
			},
			doDelegate() {
				this.checkMessage()
				this.selectUserMultipleSelect = false
				this.selectUserVisible = true
				this.selectUserType = 'delegate'
				if (this.$refs.selectUser.treeData.length == 0) {
					this.$refs.selectUser.getTreeData()
				}
			},
			selectUserFinished(selectData) {
				if (!selectData || selectData.length == 0) {
					Message.error('请先选择用户')
					return
				}
				if (this.selectUserType === 'assign') {
					putAction('/flowable/task/assign', {
						taskId: this.executeTaskId,
						userId: selectData.userId,
						message: this.form.message
					}).then(({
						msg
					}) => {
						Message.success(msg)
						this.selectUserVisible = false
						this.$emit("executeTaskFinished");
						this.queryClick()
					})
				} else if (this.selectUserType === 'delegate') {
					putAction('/flowable/task/delegate', {
						taskId: this.executeTaskId,
						userId: selectData.userId,
						message: this.form.message
					}).then(({
						msg
					}) => {
						Message.success(msg)
						this.selectUserVisible = false
						this.$emit("executeTaskFinished");
						this.queryClick()
					})
				} else if (this.selectUserType === 'selectCcTo') {
					this.ccToVos = selectData
				}
			},
			doBack() {
				this.checkMessage()
				this.dialogTaskBackNodesVisible = true
			},
			backTaskFinished(backNode) {
				putAction('/flowable/task/back', {
					taskId: this.executeTaskId,
					activityId: backNode.nodeId,
					activityName: backNode.nodeName,
					message: this.form.message
				}).then(({
					msg
				}) => {
					Message.success(msg)
					this.$emit("executeTaskFinished");
					this.queryClick()
				})
			},
			reset() {
				this.$refs.generateFormTask?.resetFields()
				this.message = undefined
				this.ccToVos = []
			},
			init() {
				this.listComments()
			},
			handleClick(tab, event) {
				if (tab.name == 'processIntanceForm') {
					this.showProcessInstanceForm();
				} else if (tab.name == 'processIntanceImage') {
					this.showImage();
				}
			},
			showProcessInstanceForm() {
				if (!this.isShowProcessInstanceForm) {
					getAction('/flowable/processInstance/formData', {
						processInstanceId: this.processInstanceId
					}).then(res => {
						const {
							data
						} = res
						this.showBusinessKey = data.showBusinessKey
						this.businessKey = data.businessKey
						if (data && data.renderedStartForm) {
							this.startFormJson = JSON.parse(data.renderedStartForm)
							this.variables = JSON.parse(data.variables.processInstanceFormData)
							this.generateStartFormVisible = true
						}
						this.isShowProcessInstanceForm = true
					})
				}
			},
			listComments() {
				getAction('/flowable/processInstance/comments', {
					processInstanceId: this.processInstanceId
				}).then(res => {
					const {
						data
					} = res
					this.comments = data;
				})
			},
			showImage() {
				if (!this.imagePath) {
					this.imagePath = `${process.env.VUE_APP_BASE_API}` +
						'/flowable/processInstanceImage?processInstanceId=' + this.processInstanceId + '&access_token=' +
						getToken() + '&time=' + new Date()
					console.log(this.imagePath)
				}
			},
			queryClick(){
				var _this = this
				getAction('/flowable/task/queryById', {
					taskId: _this.executeTaskId
				}).then(({
					data
				}) => {
					if(data.endTime==null&&data.assignee!=null&&data.assignee===this.$store.getters.sysUser.userId){
						_this.initData()
					}
					_this.endTime = data.endTime
					_this.assignee = data.assignee
				})
			},
			btnUnclaim() {
				putAction('/flowable/task/unclaim', {
					taskId: this.executeTaskId
				}).then(({
					msg
				}) => {
					Message.success(msg)
					this.queryClick()
				})
			},
			btnClaim() {
				var _this = this
				putAction('/flowable/task/claim', {
					taskId: this.executeTaskId,
				}).then(({
					msg
				}) => {
					this.queryClick()
				}).catch((response) => {
					this.queryClick()
				})
			},
			btnRead(id) {
			    let taskIds = [id]
			    if (taskIds.length == 0) {
			        Message.error('请选择要设置为已阅的记录')
			        return
			    }
			    putAction('/flowable/task/read', {taskIds}).then(({msg}) => {
			        Message.success(msg)
			        this.queryClick()
			    })
			},
		}
	}
</script>

<style scoped>
	.executeTask-box {
		padding: 25px;
	}
</style>
